<script lang="ts" setup>
import { computed, ref } from 'vue';

import { Page } from '@vben/common-ui';

import {
  Button,
  Input,
  message,
  TabPane,
  Tabs,
  Textarea,
} from 'ant-design-vue';
import TurndownService from 'turndown';
import { gfm, strikethrough, tables } from 'turndown-plugin-gfm';

import { getUrlHtml } from '#/api/tools';

const turndownService = new TurndownService({ codeBlockStyle: 'fenced' });
turndownService.use(gfm);
turndownService.use([tables, strikethrough]);
turndownService.addRule('pre2Code', {
  filter: ['pre'],
  replacement(content: string) {
    const len = content.length;
    // 除了pre标签，里面是否还有code标签包裹，有的话去掉首尾的`（针对微信文章）
    const isCode = content[0] === '`' && content[len - 1] === '`';
    const result = isCode ? content.slice(1, len - 1) : content;
    return `\`\`\`\n${result}\n\`\`\`\n`;
  },
});

const urlValue = ref('');
const urlTitle = ref('');
const htmlValue = ref('<pre>hello world!</pre>');

const mdValue = computed(() => {
  return turndownService.turndown(htmlValue.value);
});

const transformUrl = async () => {
  if (urlValue.value === '') {
    return;
  }
  message.loading({
    content: '获取url内容中...',
    duration: 0,
    key: 'url2md',
  });
  const data = await getUrlHtml(urlValue.value);
  urlTitle.value = data.title;
  htmlValue.value = data.html;
  message.destroy('url2md');
};
</script>

<template>
  <Page auto-content-height>
    <Tabs class="bg-background text-foreground h-full p-4">
      <TabPane key="1" tab="Url转Markdown">
        <div class="flex flex-col items-center">
          <div class="flex w-full flex-col items-center">
            <div class="flex w-1/2 flex-row">
              <Input
                v-model:value="urlValue"
                placeholder="请输入文章地址"
                size="large"
              />
              <Button size="large" type="primary" @click="transformUrl">
                一键转换
              </Button>
            </div>
            <Input
              v-model:value="urlTitle"
              placeholder="标题（自动读取）"
              size="large"
              class="my-4 w-1/2"
            />
          </div>
          <Textarea
            class="w-1/2"
            :auto-size="{ minRows: 28, maxRows: 28 }"
            v-model:value="mdValue"
          />
        </div>
      </TabPane>
      <TabPane key="2" tab="HTML转Markdown">
        <p class="mx-2 text-stone-500">
          Tip: 复制HTML内容到左边的文本框, 无需操作, 自动转换
        </p>
        <div class="flex flex-row">
          <Textarea
            class="m-2 w-1/2"
            :auto-size="{ minRows: 28, maxRows: 28 }"
            v-model:value="htmlValue"
          />
          <Textarea
            class="m-2 w-1/2"
            :auto-size="{ minRows: 28, maxRows: 28 }"
            v-model:value="mdValue"
          />
        </div>
      </TabPane>
    </Tabs>
  </Page>
</template>
